//
//  HMUserAccount.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMUserAccount: NSObject, NSCoding {
    
    /// 接口获取授权后的access token
    var access_token: String?
    
    // access_token的生命周期，单位是秒数, 数据类型不是文档上的String    // 157679999
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// access_token的生命周期,方便系统处理时间
    var expiresDate: Date?
    
    /// 当前授权用户的UID
    var uid: String?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    // 字典转模型 KVC
    init(dict: [String: Any]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        print("forUndefinedKey = \(key)")
    }
    
    // 对象打印信息
    override var description: String {
        let keys = ["access_token", "uid", "expires_in", "expiresDate", "screen_name", "avatar_large"]
        return dictionaryWithValues(forKeys: keys).description
    }
    
    // MARK: - 归档和解档
    /// 归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        expires_in = aDecoder.decodeDouble(forKey: "expires_in")
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
}
